<template>
  <div class="hello">
    <!-- 表格导出 -->
    <el-card shadow="hover" style="text-align: center">
      <el-card shadow="hover">
        <el-button
          v-if="this.$store.state.user.role !== 'admin'"
          type="primary"
          icon="el-icon-receiving"
          @click="qbillingData()"
          >查询实时账单</el-button
        >
        <el-button
          v-if="this.$store.state.user.role !== 'admin'"
          type="success"
          icon="el-icon-download"
          @click="exportExcel()"
          :disabled="exportdisabled"
          >导出账单表格</el-button
        >
        <div v-if="this.$store.state.user.role == 'admin'">
          用户：<el-select v-model="selectvalue" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          用户邮箱：<el-input
            style="width: 200px"
            placeholder="请输入内容"
            v-model="emailinput"
            clearable
          >
          </el-input>
          <el-button  @click="openeamil1()"
            >发送账单</el-button
          >
        </div>
        <p
          v-if="this.$store.state.user.role !== 'admin'"
          style="
            text-align: center;
            font-family: Courier New, Courier, monospace;
          "
        >
          尊敬的用户：本账单为
          <i style="color: red">当月1号～当天</i>
          账单详情数据，您可按需导出使用
        </p>
      </el-card>
    </el-card>
    <el-card shadow="hover" v-if="this.$store.state.user.role !== 'admin'">
      <span style="color: #e4e5e6"> 账单详情数据表</span>

      <el-table
        id="tableId"
        :data="billingData"
        tooltip-effect="dark"
        style="width: 100%"
        show-summary
        :summary-method="getSummaries"
        border
      >
        <el-table-column prop="username" label="调用账号" align="center">
        </el-table-column>
        <el-table-column
          prop="productName"
          width="250px"
          label="业务类型"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="clientCount" label="调用次数" align="center">
        </el-table-column>
        <el-table-column prop="successCount" label="成功次数" align="center">
        </el-table-column>

        <el-table-column prop="successCount" label="计费次数" align="center">
        </el-table-column>
        <el-table-column prop="apiKey" label="单价（元）" align="center">
          <template slot-scope="scope">{{ scope.row.apiKey }}</template>
        </el-table-column>
        <el-table-column
          prop="consume"
          sortable
          label="消费金额（元）"
          align="center"
        >
          <template slot-scope="scope">{{
            scope.row.consume | currency("￥")
          }}</template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import * as XLSX from "xlsx";
import debounce from "lodash.debounce";
import { getBill } from "@/api/order";
// import Sortable from 'sortablejs' // 该插件用于实现表格可拖拽功能，可不用，它相关的都注释了; 如果将其放开，需要在项目中安装sortablejs 插件；npm install sortablejs --save
export default {
  created() {
    //this.getbillingData();
    var d = new Date();
    var year = d.getFullYear();
    var month = d.getMonth() + 1; //得到月份
    var date = d.getDate(); //得到日期
    var hour = d.getHours(); //得到小时数
    var minute = d.getMinutes(); //得到分钟数
    var second = d.getSeconds(); //得到秒数
    // console.log(year, month, date);
    if (month) {
      this.startTime = `${year}-${month}-01 0:00:00`;
      //  console.log(this.startTime);
      this.endTime = `${year}-${month}-${date} ${hour}:${minute}:${second}`;
      //console.log(this.endTime);
    }
  },
  data() {
    return {
      //时间
      datevalue: "",
      username: localStorage.getItem("username"),
      billingData: [],
      exportdisabled: true,
      startTime: "",
      endTime: "",
      datevalue: "",
      emailinput: "",
      options: [
        {
          value: "510145",
          label: "510145",
        },
        {
          value: "RY4x0ULVLR",
          label: "RY4x0ULVLR",
        },
        {
          value: "TSNvCtd3Kn7",
          label: "TSNvCtd3Kn7",
        },
      ],
      selectvalue: "510145",
    };
  },
  mounted() {
    // this.implDropTable()
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }

        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[7] += "元";
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    setMail() {},
    //时间改变
    datechange(datevalue) {
      // console.log("时间", datevalue);
      this.datevalue = datevalue;
    },
    //发送
    // openeamil1() {
    //   if (this.emailinput == "") {
    //     this.$message({
    //       type: "info",
    //       message: "邮箱不能为空！",
    //     });
    //   } else {
    //     let res = getMail({
    //       username: this.selectvalue,
    //       mail: this.emailinput,
    //       startTime: this.startTime,
    //       endTime: this.endTime,
    //     });
    //     if (res) {
    //       this.$message({
    //         type: "success",
    //         message: "已发送账单到您的邮箱：" + value + "请注意查收！",
    //       });
    //     } else {
    //       this.$message({
    //         type: "info",
    //         message: "您取消了输入",
    //       });
    //     }
    //   }
    // },

    //邮箱填写
    openeamil() {
      this.$prompt("请输入发送账单邮箱", {
        confirmButtonText: "确定发送",
        cancelButtonText: "取消发送",
        inputPattern:
          /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        inputErrorMessage: "您的邮箱格式不正确",
      })
        .then(({ value }) => {
          getMail({ username: this.selectvalue, mail: value });

          this.$message({
            type: "success",
            message: "已发送账单到您的邮箱：" + value + "请注意查收！",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "您取消了输入",
          });
        });
    },
    //   获取数据
    async getbillingData() {
      let res = await getBill({
        username: this.username,
        startTime: this.startTime,
        endTime: this.endTime,
      });
      if (res.status == 0) {
        this.billingData = res.count.pageList;
        if (this.billingData) {
          this.exportdisabled = false;
        } else {
          this.exportdisabled = true;
        }
      }
    },
    // 查询实时数据按钮
    qbillingData: debounce(function () {
      this.getbillingData();
    }, 500),

    //   导出数据
    exportExcel: debounce(function () {
      //导出当前表格
      var wb = XLSX.utils.table_to_book(document.querySelector("#tableId")); //表格id
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "流量调用详情单.xlsx"
        ); //文件名
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }, 500),
  },
};
</script>
<style>
</style>